<?php

class LoginController extends UserBaseController
{
	public $defaultAction = 'login';

        /**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		if (Yii::app()->user->isGuest) {
		
			$model=new UserLogin;
			
			echo Yii::trace(CVarDumper::dumpAsString($model),'vardump');
			
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$this->performAjaxValidation($model);
				
				$model->attributes=$_POST['UserLogin'];
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
				
					echo Yii::trace(CVarDumper::dumpAsString($model),'vardump');
					
					$this->lastViset();
					if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false)
						$this->redirect(Yii::app()->controller->module->returnUrl);
					else
						$this->redirect(Yii::app()->user->returnUrl);
				}
			}
			// display the login form
			$this->render('/user/login',array('model'=>$model));
		} else
			$this->redirect(Yii::app()->controller->module->returnUrl);
	}
	
	/*
	private $flux_cookie_name = '';
	private $flux_cookie_seed = '';
	private $flux_cookie_hash = '';
	*/
	
	private function lastViset() {
		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
		$lastVisit->lastvisit = time();
		$lastVisit->save();
		/*
		echo Yii::trace(CVarDumper::dumpAsString($lastVisit),'vardump');
		
		require_once('./forum/config.php');
		$this->flux_cookie_name = $cookie_name;
		$this->flux_cookie_seed = $cookie_seed;
		$this->flux_cookie_hash = sha1("123e123e");//sha1($lastVisit->password);
		
		$query = "Select id from fluxbb_users where email = '".$lastVisit->email."'";
		
		$command = Yii::app()->db->createCommand($query);
		$flux_uid = $command->queryScalar();
		
		echo Yii::trace(CVarDumper::dumpAsString($flux_uid),'vardump');
		
		if (isset($flux_uid) && trim($flux_uid) != '') {
		
			$cookie_value = serialize(array($flux_uid, md5($this->flux_cookie_seed.$this->flux_cookie_hash), time() + 1209600));
			$cookie = new CHttpCookie($this->flux_cookie_name, $cookie_value);
			
			$cookie->expire = time() + 1209600;
			$cookie->domain = $cookie_domain;
			$cookie->path = $cookie_path;
			$cookie->secure = $cookie_secure;
			
			Yii::app()->request->cookies[$this->flux_cookie_name] = $cookie;
			//Yii::app()->end();
		}
		*/
	}
	
	protected function performAjaxValidation($model)
	{
		//if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		if(Yii::app()->getRequest()->getIsAjaxRequest())
		{
			$errors = CActiveForm::validate($model);
			if ($errors !== '[]') {
			   echo $errors;
			   Yii::app()->end();
			}
		}
	}

}